package com.game.frame.GameFrame.GameFrameMain;

import com.game.utils.StaticValue;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * Hero 类代表游戏中的角色对象 继承角色类
 * 它包含了角色的位置、外观、移动和绘制方法
 */
public class Hero extends BaseCharacter {
    private GameCore gameCore;
    // 添加移动状态标志
    private boolean isMovingLeft = false;
    private boolean isMovingRight = false;
    
    // 添加跳跃相关的属性
    private boolean isJumping = false;
    private double verticalVelocity = 0;
    private static final double GRAVITY = 1;
    private static final double JUMP_FORCE = -12;
    private static final int GROUND_Y = 300;  // 地面的Y坐标

    // 角色状态常量
    private static final int STATE_STANDING = 0;    // 站立
    private static final int STATE_RUNNING = 1;     // 跑步
    private static final int STATE_ATTACKING = 2;   // 攻击
    private static final int STATE_JUMPING = 3;     // 跳跃

    // 当前的状态
    private int currentState = STATE_STANDING;      // 默认为站立

    // 各个状态的动画帧范围
    private static final int[] STANDING_FRAMES = {0, 3};
    private static final int[] JUMPING_FRAMES = {3, 5};
    private static final int[] RUNNING_FRAMES = {5, 8};
    private static final int[] ATTACKING_FRAMES = {9, 13};

    // 英雄血量
    private static final int BLOOD_BAR_WIDTH = 50;
    private static final int BLOOD_BAR_HEIGHT = 3;
    private static final int BLOOD_BAR_Y_OFFSET = 6;

    // 击飞相关属性
    private boolean isKnockedBack = false;                          // 是否被击飞
    private double knockBackVelocityX = 0;                          // 击飞时在X轴上的速度
    private double knockBackVelocityY = 0;                          // 击飞时在Y轴上的速度
    private static final double KNOCK_BACK_GRAVITY = 1;           // 击飞时的重力加速度常量
    private static final double KNOCK_BACK_FORCE_X = 3.0;           // X轴上的击飞力量常量
    private static final double KNOCK_BACK_FORCE_Y = -12;           // Y轴上的击飞力量常量
    private static final int KNOCK_BACK_RECOVERY_TIME = 10;         // 击飞恢复时间常量，单位为游戏循环次数
    private int knockBackTimer = 0;                                 // 击飞计时器，用于计算击飞状态持续时间


    /**
     * 构造函数，初始化角色的位置和游戏面板
     */
    public Hero(GamePanel panel, int startX, int startY, GameCore gameCore) {
        super(panel, startX, startY, 200);
        this.attackDamage = 10000;
        this.attackRange = 1000000000;
        this.currentImage = StaticValue.perStatic;
        this.gameCore = gameCore;
    }

    /**
     * 设置角色的状态
     */
    public void setStatus(int status) {
        System.out.println(x);
        if (status == 3) {
            // 向左移动
            facingRight = false;
            currentState = STATE_RUNNING;
            if (currentFrameIndex < RUNNING_FRAMES[0] || currentFrameIndex > RUNNING_FRAMES[1]) {
                currentFrameIndex = RUNNING_FRAMES[0];
            }
            move(-5, 0);
        } else if (status == 4) {
            // 向右移动
            facingRight = true;
            currentState = STATE_RUNNING;
            if (currentFrameIndex < RUNNING_FRAMES[0] || currentFrameIndex > RUNNING_FRAMES[1]) {
                currentFrameIndex = RUNNING_FRAMES[0];
            }
            move(5, 0);
        } else if (status == 0) {
            // 静止
            currentState = STATE_STANDING;
            currentFrameIndex = STANDING_FRAMES[0];
            move(0, 0);
        } else if (status == 5 && !isJumping) {
            // 跳跃 并且不在跳跃状态 防止二段跳
            isJumping = true;
            verticalVelocity = JUMP_FORCE;
            currentState = STATE_JUMPING;
            currentFrameIndex = JUMPING_FRAMES[0];
        }
    }

    /**
     * 移动角色的位置，并检查边界条件
     */
    @Override
    protected void move(int dx, int dy) {
        int newX = x + dx;
        int newY = y + dy;

        // 检查边界
        int currentBg = gamePanel.getCurrentBgIndex();

        if (newX < 0) {
            if (currentBg > 1 && gamePanel.getBeasts().isEmpty()) {
                gamePanel.setBackgroundImage(currentBg - 1);
                x = gamePanel.getPanelWidth() - CHARACTER_WIDTH;
                // 处理场景切换
                gamePanel.getGameWindow().handleSceneChange(false); // false 表示向左
                return;
            }
        } else if (newX > gamePanel.getPanelWidth() - CHARACTER_WIDTH) {
            if (currentBg <= 4 && gamePanel.getBeasts().isEmpty()) {
                gamePanel.setBackgroundImage(currentBg == 4 ? 1 : currentBg + 1);
                x = 0;
                // 处理场景切换
                gamePanel.getGameWindow().handleSceneChange(true); // true 表示向右
                return;
            }
        }
        
        // 限制英雄在该场景内
        if (newX >= 0 && newX <= gamePanel.getPanelWidth() - CHARACTER_WIDTH) {
            x = newX;
        }

        if (newY >= 0 && newY <= gamePanel.getPanelHeight() - CHARACTER_HEIGHT) {
            y = newY;
        }
    }

    /**
     * 角色攻击
     */
    public void attack() {
        currentState = STATE_ATTACKING;
        currentFrameIndex = ATTACKING_FRAMES[0];
    }

    public void takeHit(int damage, boolean fromRight) {
        // 如果已经处于击飞状态, 不在重复触发
        if(isKnockedBack){
            return;
        }

        // 收到伤害
        takeDamage(damage);

        // 开始击飞效果
        isKnockedBack = true;
        knockBackTimer = KNOCK_BACK_RECOVERY_TIME;

        // 设置击飞速度 根据来源方向决定击飞的方向
        knockBackVelocityX = fromRight ? -KNOCK_BACK_FORCE_X : KNOCK_BACK_FORCE_X;
        knockBackVelocityY = KNOCK_BACK_FORCE_Y;
    }

    @Override
    public void updateAnimation() {
        // 如果处于击飞状态，
        if (isKnockedBack) {
            currentState = STATE_JUMPING; // 使用跳跃动画表示击飞状态
            currentFrameIndex = JUMPING_FRAMES[0];
            return;
        }
        switch (currentState) {
            case STATE_STANDING:
                currentFrameIndex++;
                if (currentFrameIndex > STANDING_FRAMES[1]) {
                    currentFrameIndex = STANDING_FRAMES[0];
                }
                break;
            case STATE_RUNNING:
                currentFrameIndex++;
                if (currentFrameIndex > RUNNING_FRAMES[1]) {
                    currentFrameIndex = RUNNING_FRAMES[0];
                }
                break;
            case STATE_ATTACKING:
                currentFrameIndex++;
                if (currentFrameIndex > ATTACKING_FRAMES[1]) {
                    currentState = STATE_STANDING;
                    currentFrameIndex = STANDING_FRAMES[0];
                }
                break;
        }

        if (facingRight) {
            currentImage = StaticValue.rightPersonImgs.get(currentFrameIndex);
        } else {
            currentImage = StaticValue.leftPersonImgs.get(currentFrameIndex);
        }

        // 更新攻击碰撞箱
        if (currentState == STATE_ATTACKING) {
            isAttacking = true;
            updateAttackBox();
            // 检查是否击中野兽
            for (Beast beast : gamePanel.getBeasts()) {
                if (!beast.isDead() && checkHit(beast)) {
                    beast.takeDamage(attackDamage);
                    gameCore.addScore(100);
                }
            }
        } else {
            isAttacking = false;
        }
    }

    /**
     * 更新物理状态方法 用于重力掉落
     */
    public void updatePhysics() {
        if(isKnockedBack){
            // 更新击飞状态
            knockBackVelocityY += KNOCK_BACK_GRAVITY;

            // 更新位置
            move((int)knockBackVelocityX, (int)knockBackVelocityY);

            // 检查是否落地
            if (y >= 300) {
                y = 300;  // 确保角色位置不会低于地面
                isKnockedBack = false;
                knockBackVelocityX = 0;
                knockBackVelocityY = 0;
                currentState = STATE_STANDING;  // 恢复站立状态
                currentFrameIndex = STANDING_FRAMES[0];
            }

            // 更新击飞计时器
            knockBackTimer--;
            if (knockBackTimer <= 0) {
                isKnockedBack = false;
                knockBackVelocityX = 0;
                knockBackVelocityY = 0;
                y = 300;
            }
        } else if (isJumping) {
            verticalVelocity += GRAVITY;
            y += verticalVelocity;

            // 是否已经落地
            if (y >= 300) {
                y = 300;
                isJumping = false;
                verticalVelocity = 0;
                currentState = STATE_STANDING;
                currentFrameIndex = STANDING_FRAMES[0];
            }
        }
    }

    /**
     * 绘制角色 以及血条
     */
    @Override
    public void drawBlood(Graphics g) {
        // 绘制角色
        g.drawImage(currentImage, x, y, CHARACTER_WIDTH, CHARACTER_HEIGHT, null);

        // 计算血条位置（居中显示）
        int bloodBarX = x + (CHARACTER_WIDTH - BLOOD_BAR_WIDTH) / 2;
        int bloodBarY = y + BLOOD_BAR_Y_OFFSET;

        // 绘制血条背景（灰色）
        g.setColor(Color.GRAY);
        g.fillRect(bloodBarX, bloodBarY, BLOOD_BAR_WIDTH, BLOOD_BAR_HEIGHT);

        // 绘制当前血量（绿色）
        g.setColor(Color.GREEN);
        int currentBloodWidth = (int)((float)health / 200 * BLOOD_BAR_WIDTH);
        g.fillRect(bloodBarX, bloodBarY, currentBloodWidth, BLOOD_BAR_HEIGHT);
    }
}
